package com.ewhale.feitengguest.ui.user.mine;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.ewhale.feitengguest.R;
import com.ewhale.feitengguest.dto.ArticleDetailDto;
import com.ewhale.feitengguest.dto.VersionDto;
import com.ewhale.feitengguest.presenter.user.mine.SettingPresenter;
import com.ewhale.feitengguest.ui.WebViewActivity;
import com.ewhale.feitengguest.ui.user.MainActivity;
import com.ewhale.feitengguest.utils.Contants;
import com.ewhale.feitengguest.utils.UserInfoUtils;
import com.ewhale.feitengguest.view.user.mine.SettingView;
import com.ewhale.feitengguest.widget.VersionDialog;
import com.orhanobut.hawk.Hawk;
import com.simga.library.activity.MBaseActivity;
import com.simga.library.utils.AppManager;
import com.simga.library.utils.DataCleanManager;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.SystemUtil;
import com.simga.library.widget.HintDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jiguang.share.android.api.JShareInterface;
import cn.jiguang.share.qqmodel.QQ;
import cn.jiguang.share.wechat.Wechat;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class SettingActivity extends MBaseActivity<SettingPresenter> implements SettingView, EasyPermissions.PermissionCallbacks {
    @BindView(R.id.tv_cache)
    TextView mTvCache;
    @BindView(R.id.tv_version)
    TextView mTvVersion;
    private HintDialog hintDialog;
    private static final int REQUEST_CODE_PERMISSION = 10001;

    public static void open(MBaseActivity context) {
        context.startActivity(null, SettingActivity.class);
    }

    @Override
    protected int getViewId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setTitle("设置");
        try {
            mTvCache.setText(DataCleanManager.getTotalCacheSize(mContext));
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTvVersion.setText("当前版本: " + SystemUtil.getVersionName(mContext));
    }

    @Override
    protected boolean isUseBaseTitleBar() {
        return true;
    }

    @Override
    public void showProLoading() {
        showLoading();
    }

    @Override
    public void dimissProLoading() {
        dismissLoading();
    }

    @Override
    public void showErrorMessage(int postCode, String code, String message) {
        showErrorMsg(code, message);
    }

    @OnClick({R.id.rl_helpcenter, R.id.rl_feelback, R.id.rl_clean_cache,
            R.id.rl_version_update, R.id.rl_cooperation, R.id.btn_login_out,
            R.id.rl_call_service, R.id.tv_xieyi, R.id.tv_privacy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_helpcenter:
                HelpCenterActivity.open(mContext);
                break;
            case R.id.rl_feelback:
                FeelBackActivity.open(mContext);
                break;
            case R.id.rl_clean_cache:
                hintDialog = new HintDialog(mContext, "提示", "您确定清理缓存吗？", new String[]{"取消", "确定"});
                hintDialog.setCallback(new HintDialog.Callback() {
                    @Override
                    public void callback() {
                        DataCleanManager.clearAllCache(mContext);
                        mTvCache.setText("0K");
                    }

                    @Override
                    public void cancle() {
                    }
                });
                hintDialog.show();
                break;
            case R.id.rl_version_update:
                presenter.checkVersion();
                break;
            case R.id.rl_cooperation:
                presenter.loadArticleDetails(4);
                break;
            case R.id.btn_login_out:
                hintDialog = new HintDialog(mContext, "提示", "确定退出登录？", new String[]{"取消", "确定"});
                hintDialog.setCallback(new HintDialog.Callback() {
                    @Override
                    public void callback() {
                        if (Hawk.get(HawkKey.NOW_APP_STATUS, Contants.USER_STATUS).equals(Contants.SHOP_STATUS)) {
                            sendBroadcast(new Intent(HawkKey.SHOP_LOGIN_OUT));
                            MainActivity.open(mContext);
                        } else {
                            sendBroadcast(new Intent(HawkKey.USER_LOGIN_OUT));
                        }
                    }

                    @Override
                    public void cancle() {
                    }
                });
                hintDialog.show();
                break;
            case R.id.rl_call_service:
                requestCallPhone();
                break;
            case R.id.tv_xieyi:
                presenter.loadArticleDetails(1);
                break;
            case R.id.tv_privacy:
                presenter.loadArticleDetails(11);
                break;
        }
    }

    @Override
    public void showDetail(ArticleDetailDto result, int type) {
        if (type == 1) {
            WebViewActivity.open(mContext, "用户协议", result.content);
        } else if (type == 4) {
            WebViewActivity.open(mContext, "商家合作", result.content);
        } else if (type == 11) {
            WebViewActivity.open(mContext, "隐私保护协议", result.content);
        }
    }

    @Override
    public void showVersion(VersionDto result) {
        if (result.getVersion().equals(SystemUtil.getVersionName(mContext))) {
            showToast("当前版本已是最新版本");
        } else {
            VersionDialog mDialog = new VersionDialog(mContext, result.getContent(), result.getIsForce());
            mDialog.setListenter(() -> {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");
                Uri content_url = Uri.parse(result.getUrl());
                intent.setData(content_url);
                startActivity(intent);
            });
            mDialog.setOnDismissListener(dialog -> {
                if (result.getIsForce() == 1) {//是否强更新   是
                    Hawk.deleteAll();
                    //退出整个APP
                    System.exit(0);
                }
            });
            mDialog.show();
        }
    }


    @AfterPermissionGranted(REQUEST_CODE_PERMISSION)
    private void requestCallPhone() {
        String[] perms = new String[]{Manifest.permission.CALL_PHONE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            Intent intent = new Intent(Intent.ACTION_CALL);
            Uri data = Uri.parse("tel:" + "0769-82387890");
            intent.setData(data);
            startActivity(intent);
        } else {
            EasyPermissions.requestPermissions(this, "申请获取相关权限",
                    REQUEST_CODE_PERMISSION, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:" + "0769-82387890");
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle("权限申请")
                    .setRationale("申请获取相关权限")
                    .setPositiveButton(getString(R.string.comfir))
                    .setNegativeButton(getString(R.string.cancle))
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
